<template>
  <v-dialog
    v-model="dialogFormVisible"
    :title="title"
    max-width="850px"
    persistent
    @update:model-value="close"
  >
    <v-card>
      <v-card-title>{{ title }}</v-card-title>
      
      <v-card-text>
        <v-form
          ref="form"
          v-model="valid"
          :loading="formLoading"
          class="orgManagement-edit-container"
        >
          <v-row>
            <!-- 上级机构 -->
            <v-col cols="12" md="6">
              <v-text-field
              v-model="parentOrg.orgName"
                label="上级机构"
                readonly
                @click="showParentOrg"
                append-inner-icon="mdi-magnify"
              ></v-text-field>
              <v-btn
                icon
                color="primary"
                class="input-btn-choose"
                      :disabled="true"
                @click="showParentOrg"
                style="margin-top: -48px; margin-left: 220px;"
              >
                <v-icon>mdi-magnify</v-icon>
              </v-btn>
            </v-col>

            <!-- 编号 -->
            <v-col cols="12" md="6">
              <v-tooltip
                :text="'自动继承父级编号: ' + parentOrg.orgCode + '_'"
                location="top"
                :model-value="codeTip"
                manual
              >
                <template v-slot:activator="{ props }">
                  <v-text-field
                    v-model="form.orgCode"
                    label="编号"
                    :disabled="!formStatus"
                    v-bind="props"
                    :rules="[
                      v => !!v || '请输入编号',
                      v => validatorRule.IS_GENERAL(v) || '编号格式不正确'
                    ]"
                  ></v-text-field>
                </template>
              </v-tooltip>
            </v-col>

            <!-- 名称 -->
            <v-col cols="12" md="6">
              <v-text-field
                v-model="form.orgName"
                label="名称"
                :rules="[
                  v => !!v || '请输入名称',
                  v => validatorRule.IS_GENERAL_WITH_CHINESE(v) || '名称格式不正确'
                ]"
              ></v-text-field>
            </v-col>

            <!-- 排序 -->
            <v-col cols="12" md="6">
              <v-text-field
                v-model="form.sortNo"
                label="排序"
                type="number"
              :min="1"
              :max="500"
                :rules="[v => !!v || '请输入排序']"
              ></v-text-field>
            </v-col>

            <!-- 备注 -->
            <v-col cols="12" md="6">
              <v-textarea
                v-model="form.remark"
                label="备注"
                rows="3"
              ></v-textarea>
            </v-col>
          </v-row>
        </v-form>
      </v-card-text>

      <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn @click="close">取消</v-btn>
        <v-btn color="primary" @click="save">确定</v-btn>
      </v-card-actions>
    </v-card>

    <tenant
      v-on:tenant="closeTenant"
      ref="tenant"
    ></tenant>

    <org-single-choose
      ref="orgSingleChooseRef"
      @choose="orgSingleChoose"
    ></org-single-choose>
  </v-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { get, doInsert, doUpdate } from "@/api/system/org/orgManagement";
import { deepClone } from "@/utils/clone";
import { isNull } from "@/utils/validate"; 
import { validatorRule } from "@/utils/validateRule";
import { useMessage } from "@/composables/useMessage";
import OrgSingleChoose from "@/components/opsli/org/OrgSingleChoose.vue";

const { success: showSuccess } = useMessage();

const codeTip = ref(false);
const formStatus = ref(true);
const genParentId = ref("");
const edenOldParentId = ref("");
const oldParentId = ref("");
const parentOrg = ref<any>({});
const form = ref<any>({
  parentId: "0",
  tenantId: "",
  sortNo: 1,
  version: 0,
  orgCode: "",
  orgName: "",
  remark: ""
});
const dict = ref({});
const title = ref("");
const formLoading = ref(true);
const dialogFormVisible = ref(false);
const valid = ref(false);
const formRef = ref<any>();
const tenant = ref<any>();
const orgSingleChooseRef = ref<any>();

const showTenant = () => {
  (tenant.value as any)?.show();
};

const closeTenant = (val: any) => {
  form.value.tenantId = val.id;
};

const orgSingleChoose = (node: any) => {
  parentOrg.value = node;
  form.value.parentId = parentOrg.value.id;
};

const showParentOrg = () => {
  return;
  // TODO 因为逻辑问题 不允许更换上级机构
  if(edenOldParentId.value && formStatus.value){
    return;
  }
  orgSingleChooseRef.value?.showOrgChoose(form.value.id);
};

const showEdit = (row?: any) => {
  if (isNull(row) || isNull(row?.id)) {
    title.value = "添加机构";
    // 如果上级菜单名称不为空 则显示到标题上
    if(!isNull(row) && !isNull(row.parentName) &&
      !isNull(row.parentId) && !isNull(row.parentCode)){
      // 设置上级Id
      edenOldParentId.value = row.parentId;
      form.value.parentId = row.parentId;
    }
  } else {
    title.value = "编辑机构";
    formStatus.value = false;
    form.value = Object.assign({}, row);
  }

  // 设置 编号提醒项
  if(formStatus.value && edenOldParentId.value){
    setTimeout(() => {
      codeTip.value = true;
    }, 200);
  }

  oldParentId.value = form.value.parentId;

  dialogFormVisible.value = true;
  // 加载上级菜单数据
  fetchData();
};

const close = () => {
  dialogFormVisible.value = false;
  formRef.value?.reset();
  form.value = {
    parentId: "0",
    tenantId: "",
    sortNo: 1,
    version: 0,
    orgCode: "",
    orgName: "",
    remark: ""
  };
  codeTip.value = false;
  formStatus.value = true;
  formLoading.value = true;
  edenOldParentId.value = "";
  oldParentId.value = "";
  genParentId.value = "";
};

const save = async () => {
  const { valid } = await formRef.value?.validate();
  if (valid) {
    // 字段数据
    let tmpForm = deepClone(form.value);

    // 修改
    if (!isNull(tmpForm.id)) {
      const response = await doUpdate(tmpForm);
      showSuccess(response.data?.msg || "更新成功");
    } else {
      // 如果上级code不为空 则在新增是 拼上上级code
      if(!isNull(parentOrg.value.orgCode)){
        tmpForm.orgCode = parentOrg.value.orgCode + "_" + tmpForm.orgCode;
      }
      const response = await doInsert(tmpForm);
      showSuccess(response.data?.msg || "添加成功");
    }

    // 刷新标签
    if(!isNull(oldParentId.value)){
      emit("refreshNodeBy", oldParentId.value);
    }
    if(!isNull(parentOrg.value.parentId)){
      emit("refreshNodeBy", parentOrg.value.parentId);
    }
    emit("refreshNodeBy", form.value.parentId);

    close();
  }
};

const fetchData = async () => {
  formLoading.value = true;
  const { data } = await get({id: form.value.parentId});
        if(data){
    parentOrg.value = data;
        }

        setTimeout(() => {
    formLoading.value = false;
        }, 300);
  };

const emit = defineEmits(['refreshNodeBy']);

// 暴露方法给父组件使用
defineExpose({
  showEdit
});
</script>

<style scoped>
.orgManagement-edit-container {
  padding: 10px 0;
}
.input-btn-choose {
  position: absolute;
  right: 10px;
  top: 32px;
  z-index: 2;
}
</style>
